20180727 Google Maps API -台南火車站附近餐廳查詢練習
前面已經教學如何使用google maps api在python上,
現在我們來做簡單的練習試試看。
#導入模組&設定憑證
import googlemaps
import time #python內建的時間模組後面設定間隔時間會用到
gmaps=googlemaps.Client(key="這裡輸入你的API KEY")
#取得台南火車站的地理編碼
geocode_result = gmaps.geocode("台南火車站")
地址編碼輸出結果會像下面這樣,
結果為只有一項的list,以dict的方式呈現,
其中包含經緯度資訊(location)以及GMAP的地點資訊ID(place_id)
gecode_result
###output###
[{'address_components': [{'long_name': '赤嵌里',
'short_name': '赤嵌里',
'types': ['administrative_area_level_4', 'political']},
{'long_name': '台南市',
'short_name': '台南市',
'types': ['administrative_area_level_1', 'political']},
{'long_name': 'Taiwan',
'short_name': 'TW',
'types': ['country', 'political']}],
'formatted_address': 'Taiwan, 台南市赤嵌里',
'geometry': {'location': {'lat': 22.9972343, 'lng': 120.211936},
'location_type': 'GEOMETRIC_CENTER',
'viewport': {'northeast': {'lat': 22.9985832802915,
'lng': 120.2132849802915},
'southwest': {'lat': 22.9958853197085, 'lng': 120.2105870197085}}},
'place_id': 'ChIJGzRaiYx2bjQRMBm7h8aVNzc',
'plus_code': {'compound_code': 'X6W6+VQ Tainan, 東區台南市 Taiwan',
'global_code': '7QJ2X6W6+VQ'},
'types': ['establishment', 'point_of_interest', 'transit_station']}]
試著找出台南火車站附近100公尺的餐廳,
使用gmaps.place_radar的語法,如下:
(更多語法示例,參考這個: google-maps-services-python 的 place usage example)
#把台南火車站的經緯度取出來定義為loc,訂一個半徑變數叫rad
loc = geocode_result[0]['geometry']['location']
rad = 100
#用gmaps.places_radar這個代碼來查total有幾個結果
print("台南火車站為中心"+str(rad)+"公尺的餐廳數量: "+
str(len(gmaps.places_radar(keyword="餐廳",location=loc, radius=rad)['results'])))
###Output###
台南火車站為中心100公尺的餐廳數量: 6
其中gmaps.places_radar輸出的結果與前面類似,一樣有經緯資訊和place_id,
我們將place_id取出來,用迴圈家道pids這個list之中
pids=[]
for place in gmaps.places_radar(keyword="餐廳", location=loc, radius=rad)['results']:
pids.append(place['place_id']) #只取出result裡面place_id的部分加到list裏頭
再來我們使用gmaps.place的語法再取出地點資訊,
加到restaurant_info這個list裏頭,
其中我讓每次request中間隔0.3秒,原因是太快容易造成取聯繫API timeout。 (待確認)
restaurant_info = []
for id in pids:
print ("running")
restaurant_info.append(gmaps.place(place_id=id, language='zh-TW')['result'])
#每次間隔0.3sec
time.sleep(0.3)
gmaps.place取得的資訊非常多龐大,
所以現在restaurant_info裏頭包含非常複雜的資料,
最雞肋我們可以簡單取出要的訊息就好,
(各位可以試試看print restaurant_info[0]來查看裡面到底有什麼訊息)
如下取得餐廳名稱:
for r in restaurant_info:
print (r['name'])
###output###
(台南大飯店)歐式自助餐
爭鮮迴轉壽司-台南店
台南大飯店港式飲茶
台南大飯店
爭鮮外帶壽司-台南台鐵店
(台南大飯店)食選任意點
或是可以用pandas來整理資料 (python 的一個數據分析 lib),
也許後面我們有機會來介紹。